import React, { Component } from 'react';
import ReactDom from 'react-dom';
import util from "@/common/util";
import ReactSwiper from 'reactjs-swiper';
import jquery from 'jquery';


class Article extends Component {
    constructor(props) {
        super(props);
        this.state = {
            images: [
                //里面的数据参数是固定的 image代表src link代表a链接 title代表图片说明
                //{ image: '', title: '', link: '' }，{ image: '', title: '', link: '' }
            ],
            cardList: [],
            newslist: []
        }
    }

    async sendcode() {
        var wechatcode = util.getQuery().code;
        let res = await util.rjax({
            url: '/wxAuthenticate/getOpenId?code=' + wechatcode,
            type: 'post',
        }).catch((res) => {
            console.log("catch:" + res)
        })

        if (res) {
            console.log("if(res):" + res)
            sessionStorage.setItem("openid", res.data.openId)
        }
    }

    componentDidMount() {
        if (util.getQuery().code) {
            var openid = sessionStorage.getItem("openid")
            if (!openid || openid === 'null') {
                this.sendcode()
            }
        }
        else {
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxeaccffdd3826280c&redirect_uri=http%3a%2f%2fwww.rongsue.com%2fwechat%2farticle.html&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect`
        }

        let getconfig = async function () {
            let res = await util.rjax({
                url: "/wx/getwx?url=" + encodeURIComponent(window.location.href.split('#')[0]),
                type: "POST"
            })

            if (res) {
                wx.config({
                    debug: false,
                    appId: 'wxeaccffdd3826280c', // 必填，公众号的唯一标识
                    timestamp: parseInt(res.data.timestamp),// 必填，生成签名的时间戳
                    nonceStr: res.data.nonceStr,// 必填，生成签名的随机串
                    signature: res.data.signature,// 必填，签名
                    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']// 必填，需要使用的JS接口列表
                })
            }
        }
        getconfig()

        wx.ready(function () {
            //朋友圈
            wx.onMenuShareTimeline({// 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口（即将废弃）
                title: '苏门e栈精选文章', // 分享标题
                link: 'http://www.rongsue.com/wechat/article.html', // 分享链接
                imgUrl: 'http://img0.rongsue.com/FjJfUOJNyevdklC8vj4XtVht8heD',
                success: function (res) {
                },
                cancel: function (res) {
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });

            //朋友
            wx.onMenuShareAppMessage({//获取“分享给朋友”按钮点击状态及自定义分享内容接口（即将废弃）
                title: '苏门e栈精选文章', // 分享标题
                desc: '最新行业资讯，专业解析知识都在这里', // 分享描述
                link: 'http://www.rongsue.com/wechat/article.html', // 分享链接
                imgUrl: 'http://img0.rongsue.com/FjJfUOJNyevdklC8vj4XtVht8heD', // 分享图标
                type: '', // 分享类型,music、video或link，不填默认为link
                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                },
                fail: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        });

        var that = this;
        jquery('.type').find('span').click(function () {
            var id = jquery(this).data('id')
            that.newslist(id)
        })

        this.getBannerList()
        this.newslist()
    }

    async  getBannerList() {
        let res = await util.rjax({
            url: '/banner/list?type=0',
            type: 'get',
        })
        this.setState({ images: res.data.rows })
    }


    async newslist(id) {
        if (!id || id === "null") {
            id = 0
        }
        let res = await util.rjax({
            url: '/news/getList?type=1&kind=' + id,
            type: 'get'
        })
        this.setState({ newslist: res.data });
    }

    render() {
        const swiperOptions = {
            preloadImages: true,
            autoplay: 5000,
            autoplayDisableOnInteraction: false,
            spaceBetween: 0
            // direction: 'vertical'
        };
        let newslist = this.state.newslist.map((item, index) => {
            return (
                <li data-id={item.id} key={index}>
                    <a href={item.urlLink}>
                        <img src={item.image} alt="" />
                        <div>
                            <p className="tit">{item.title}</p>
                            <p className="intr">{item.summary}</p>
                        </div>
                    </a>
                </li>
            )
        })

        return (
            <div>
                <div id="article">
                    <ReactSwiper options={swiperOptions} showPagination items={this.state.images} />
                    {/* type */}
                    <div className="type">
                        <img src="/assets/wechat/btn_three.png" alt="" />
                        <span data-id="0">小知识</span>
                        <span data-id="1" >案例</span>
                        <span data-id="2">申卡</span>
                    </div>
                    {/* article */}
                    <div className="article">
                        <ul>
                            {newslist}
                        </ul>
                    </div>
                </div>
            </div>
        )
    }
}
ReactDom.render(<Article />, document.getElementById("app"));